package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     *
     * @param dishDto
     */

    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {

        //首先保存菜品的基本信息到菜品表dish中
        this.save(dishDto);


        //
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();

        for(DishFlavor dishFlavor:flavors)
        {
            dishFlavor.setDishId(dishId);
        }
        //保存菜品的口味信息到口味表dishflavor中
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品信息和口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        //查询菜品基本信息
        Dish dish = this.getById(id);

        //查询口味信息
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(id != null, DishFlavor::getDishId, dish.getId());

        List<DishFlavor> list = dishFlavorService.list(lambdaQueryWrapper);

        //对象拷贝
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Transactional
    @Override
    public void updateWithFlavor(DishDto dishDto) {

        //首先保存菜品的基本信息到菜品表dish中
        this.updateById(dishDto);

        //先清除flavor的内容,delete
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);

        //再新建flavor的内容,save
        List<DishFlavor> flavors = dishDto.getFlavors();
        for(DishFlavor dishFlavor:flavors)
        {
            dishFlavor.setDishId(dishDto.getId());
        }

        dishFlavorService.saveBatch(flavors);

    }
}
